package org.jeecg.modules.oa.controller;

import java.util.*;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.hutool.core.collection.CollectionUtil;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.SsoUtil;
import org.jeecg.common.util.StringUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.oa.entity.OaComment;
import org.jeecg.modules.oa.entity.OaJournal;
import org.jeecg.modules.oa.entity.OaReportWeek;
import org.jeecg.modules.oa.service.IOaCommentService;
import org.jeecg.modules.oa.service.IOaJournalService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.oa.service.IOaReportWeekReadService;
import org.jeecg.modules.oa.service.IOaReportWeekService;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.entity.SysPosition;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.system.service.ISysPositionService;
import org.jeecg.modules.system.service.ISysUserRoleService;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * @Description: 工作日志表
 * @Author: jeecg-boot
 * @Date: 2019-09-11
 * @Version: V1.0
 */
@Slf4j
@Api(tags = "工作日志表")
@RestController
@RequestMapping("/b/oaJournal")
public class OaJournalController {
    @Autowired
    private IOaJournalService oaJournalService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysDepartService departService;
    @Autowired
    private IOaCommentService oaCommentService;
    @Autowired
    private IOaReportWeekReadService readService;
    @Autowired
    private ISysPositionService positionService;

    @Autowired
    private IOaReportWeekService reportWeekService;

    @Autowired
    private ISysUserRoleService sysUserRoleService;

    /**
     * 自定义分页列表查询
     *
     * @param oaJournal
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "工作日志表-分页列表查询")
    @ApiOperation(value = "工作日志表-分页列表查询", notes = "工作日志表-分页列表查询")
    @GetMapping(value = "/list2")
    public Result<IPage<OaJournal>> queryPageList2(OaJournal oaJournal,
                                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                   HttpServletRequest req) {

        List<String> departIds = sysUserRoleService.queryDepartIds(oaJournal);
        System.out.println(departIds.toString());
        String departStr = "AND o.id in ('')";
        if(departIds.size() > 0){
            departStr = " AND o.id in ('"+String.join("','",departIds)+"')";
        }
        Result<IPage<OaJournal>> result = new Result<>();
        Page<OaJournal> page = new Page<>(pageNo, pageSize);
        page = oaJournalService.findPcAllList(page, oaJournal,departStr);
        return getResule(page, result);
    }


    /**
     * 按用户名字自定义分页列表查询历史日志
     *
     * @param oaJournal
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "工作日志表-分页列表查询")
    @ApiOperation(value = "工作日志表-分页列表查询", notes = "工作日志表-分页列表查询")
    @GetMapping(value = "/byNameList")
    public Result<IPage<OaJournal>> byNameListPage(OaJournal oaJournal,
                                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                   HttpServletRequest req) {
        Result<IPage<OaJournal>> result = new Result<IPage<OaJournal>>();
        Page<OaJournal> page = new Page<OaJournal>(pageNo, pageSize);
        page = oaJournalService.listByUserPage(page, oaJournal);
        return getResule(page, result);
    }

    /**
     * 获取当前用户的今日日志
     * @param req
     * @return
     */
    @RequestMapping(value = "/getJournal")
    @ResponseBody
    public Result<OaJournal> getJournal(HttpServletRequest req) {
        Result<OaJournal> result = new Result<OaJournal>();
        LoginUser user = SsoUtil.getLoginUser();
        OaJournal journal = oaJournalService.getByCreateByAndToday(user.getId());
        if(journal!=null){
            result.setResult(journal);
            result.setSuccess(true);
        }else{
            result.setSuccess(false);
            result.setMessage("暂无今日日志");
        }
        return result;
    }

    /**
     * 当前用户的日志
     *
     * @param oaJournal
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "我的工作日志表-分页列表查询")
    @ApiOperation(value = "我的工作日志表-分页列表查询", notes = "我的工作日志表-分页列表查询")
    @GetMapping(value = "/myList")
    public Result<IPage<OaJournal>> queryPageMyList(OaJournal oaJournal,
                                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                    HttpServletRequest req) {
        LoginUser sysUser = SsoUtil.getLoginUser();
        oaJournal.setCreateBy(sysUser.getId());
        Result<IPage<OaJournal>> result = new Result<IPage<OaJournal>>();
        Page<OaJournal> page = new Page<OaJournal>(pageNo, pageSize);
        page = oaJournalService.findPcAllList(page, oaJournal,"");
        return getResule(page, result);
    }

    /**
     * 分页列表查询
     *
     * @param oaJournal
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "工作日志表-分页列表查询")
    @ApiOperation(value = "工作日志表-分页列表查询", notes = "工作日志表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<OaJournal>> queryPageList(OaJournal oaJournal,
                                                  @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                  @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                  HttpServletRequest req) {
        Result<IPage<OaJournal>> result = new Result<IPage<OaJournal>>();
        QueryWrapper<OaJournal> queryWrapper = QueryGenerator.initQueryWrapper(oaJournal, req.getParameterMap());
        Page<OaJournal> page = new Page<OaJournal>(pageNo, pageSize);
        IPage<OaJournal> pageList = oaJournalService.page(page, queryWrapper);
        if (pageList != null && CollectionUtil.isNotEmpty(pageList.getRecords())) {
            SysUser createUser;
            for (OaJournal oj : pageList.getRecords()) {
                if (StringUtils.isNotBlank(oj.getCreateBy())) {
                    createUser = sysUserService.getById(oj.getCreateBy());
                    if (createUser != null) {
                        oj.setSysUser(createUser);
                    }
                }
            }
        }
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    /**
     * 添加
     *
     * @param oaJournal
     * @return
     */
    @AutoLog(value = "工作日志表-添加")
    @ApiOperation(value = "工作日志表-添加", notes = "工作日志表-添加")
    @PostMapping(value = "/add")
    public Result<OaJournal> add(@RequestBody OaJournal oaJournal) {
        Result<OaJournal> result = new Result<OaJournal>();
        LoginUser loginUser = SsoUtil.getLoginUser();
        OaJournal journal = oaJournalService.getByCreateByAndToday(loginUser.getId());
        if(journal!=null){//一天只能新增一次周报
            result.setSuccess(false);
            result.setMessage("今日日志已经存在，不允许重复提交");
            return result;
        }
        oaJournal.setCreateBy(loginUser.getId());
        oaJournal.setInputTime(new Date());
        oaJournal.setHits(0);
        try {
            oaJournalService.save(oaJournal);
            result.success("添加成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    /**
     * 编辑
     *
     * @param oaJournal
     * @return
     */
    @AutoLog(value = "工作日志表-编辑")
    @ApiOperation(value = "工作日志表-编辑", notes = "工作日志表-编辑")
    @PutMapping(value = "/edit")
    public Result<OaJournal> edit(@RequestBody OaJournal oaJournal) {
        Result<OaJournal> result = new Result<OaJournal>();
        OaJournal oaJournalEntity = oaJournalService.getById(oaJournal.getId());
        if (oaJournalEntity == null) {
            result.error500("未找到日志");
        } else {
            oaJournal.setUpdateTime(new Date());
            boolean ok = oaJournalService.updateById(oaJournal);
            if (ok) {
                result.success("修改成功!");
            }
        }

        return result;
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "工作日志表-通过id删除")
    @ApiOperation(value = "工作日志表-通过id删除", notes = "工作日志表-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        try {
            oaJournalService.removeById(id);
        } catch (Exception e) {
            log.error("删除失败{}", e.getMessage());
            return Result.error("删除失败!");
        }
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "工作日志表-批量删除")
    @ApiOperation(value = "工作日志表-批量删除", notes = "工作日志表-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<OaJournal> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        Result<OaJournal> result = new Result<OaJournal>();
        if (ids == null || "".equals(ids.trim())) {
            result.error500("参数不识别！");
        } else {
            this.oaJournalService.removeByIds(Arrays.asList(ids.split(",")));
            result.success("删除成功!");
        }
        return result;
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "工作日志表-通过id查询")
    @ApiOperation(value = "工作日志表-通过id查询", notes = "工作日志表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<OaJournal> queryById(@RequestParam(name = "id", required = true) String id) {
        Result<OaJournal> result = new Result<OaJournal>();
        OaJournal oaJournal = oaJournalService.getById(id);
        if (oaJournal == null) {
            result.error500("未找到对应实体");
        } else {
            result.setResult(oaJournal);
            result.setSuccess(true);
        }
        return result;
    }

    /**
     * 导出excel
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, HttpServletResponse response) {
        // Step.1 组装查询条件
        QueryWrapper<OaJournal> queryWrapper = null;
        try {
            String paramsStr = request.getParameter("paramsStr");
            if (oConvertUtils.isNotEmpty(paramsStr)) {
                String deString = URLDecoder.decode(paramsStr, "UTF-8");
                OaJournal oaJournal = JSON.parseObject(deString, OaJournal.class);
                queryWrapper = QueryGenerator.initQueryWrapper(oaJournal, request.getParameterMap());
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        List<OaJournal> pageList = oaJournalService.list(queryWrapper);
        //导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "工作日志表列表");
        mv.addObject(NormalExcelConstants.CLASS, OaJournal.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("工作日志表列表数据", "导出人:Jeecg", "导出信息"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<OaJournal> listOaJournals = ExcelImportUtil.importExcel(file.getInputStream(), OaJournal.class, params);
                oaJournalService.saveBatch(listOaJournals);
                return Result.ok("文件导入成功！数据行数:" + listOaJournals.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.ok("文件导入失败！");
    }

    /**
     * 保存留言
     *
     * @param oaComment
     * @return
     */
    @RequestMapping(value = "/saveComment")
    public Result<List<OaComment>> saveComment(OaComment oaComment) {
        Result<List<OaComment>> result = new Result<List<OaComment>>();
        if (oaComment != null) {
            LoginUser loginUser = SsoUtil.getLoginUser();
            SysUser user = sysUserService.getById(loginUser.getId());
            oaComment.setCreateBy(user.getId());
            oaComment.setActualBy(user.getId());//真实评论者
            //oaComment.setTopicType("JG001");
            oaComment.setCreateDepatr(user.getDepartId());
            oaCommentService.save(oaComment);
            result.setResult(oaCommentService.findAllMsgById(user.getId(),oaComment.getTopicId()));
        }
        return result;
    }

    /**
     * 获取留言
     *
     * @param oaComment
     * @return
     */
    @RequestMapping(value = "/getComment")
    public Result<List<OaComment>> getComment(OaComment oaComment) {
        Result<List<OaComment>> result = new Result<List<OaComment>>();
        LoginUser loginUser = SsoUtil.getLoginUser();
        SysUser user = sysUserService.getById(loginUser.getId());
        // 日志阅读详情saveOrupdate
        readService.updateReadInfo(oaComment.getTopicId(), true, user);

        if(CommonConstant.TOPIC_TYPE_REPORT_DAY.equals(oaComment.getTopicType())){
            // 日志点击数+1
            OaJournal oj = oaJournalService.getById(oaComment.getTopicId());
            Integer hits = oj.getHits();
            oj.setHits((hits == null ? 0 : hits) + 1);
            oaJournalService.updateById(oj);
        }else if(CommonConstant.TOPIC_TYPE_REPORT_WEEK.equals(oaComment.getTopicType())){
            // 周报点击数+1
            OaReportWeek oj = reportWeekService.getById(oaComment.getTopicId());
            Integer hits = oj.getHits();
            oj.setHits((hits == null ? 0 : hits) + 1);
            reportWeekService.updateById(oj);
        }

        if (StringUtils.isNotBlank(oaComment.getTopicId())) {
            return Result.ok(oaCommentService.findAllMsgById(user.getId(),oaComment.getTopicId()));
        }
        return result;
    }

    private Result<IPage<OaJournal>> getResule(Page<OaJournal> page, Result<IPage<OaJournal>> result) {
        if (CollectionUtil.isNotEmpty(page.getRecords())) {
            for (OaJournal oj : page.getRecords()) {
                if (oj != null) {
                    Map map = new HashMap<>();
                    map.put("departName", oj.getDepartName());
                    map.put("departId", oj.getDepartId());
                    map.put("companyId", oj.getCompanyId());
                    map.put("companyName", oj.getCompanyName());
                    map.put("createBy", oj.getCreateBy());
                    map.put("createName", oj.getCreateName());
                    map.put("userName", oj.getUsername());
                    map.put("positionId", oj.getPositionId());
                    map.put("positionCode", oj.getPositionCode());
                    map.put("positionName", oj.getPositionName());
                    map.put("createTime", oj.getCreateTime());
                    oj.setMap(map);
                }
            }
        }
        result.setResult(page);
        result.setSuccess(true);
        return result;
    }

    /**
     * 岗位列表
     *
     * @return
     */
    @RequestMapping(value = "/selectPosition")
    public Result<List<SysPosition>> selectPosition(HttpServletRequest req) {
        Result<List<SysPosition>> result = new Result<>();
        List<SysPosition> lists =new LinkedList<>();
        List<SysPosition> all = positionService.getAll();
        if(CollectionUtil.isNotEmpty(all)){//解决页面无全部选项
            SysPosition sp=new SysPosition();
            sp.setName("全部");
            sp.setId("");
            sp.setCode("");
            lists.add(sp);
            lists.addAll(all);
        }
        result.setResult(lists);
        result.setSuccess(true);
        return result;
    }

}
